package com.sc.highspeed.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.highspeed.controller.result.JsonResult;
import com.sc.highspeed.db.model.UrgInformationModel;
import com.sc.highspeed.service.UrgInformationService;
import com.sc.highspeed.service.UserService;
import com.sc.highspeed.websocket.WebSocketEndPoint;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.ant.taskdefs.Exec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static com.sc.highspeed.constant.Constant.pageSize;
/**
 * Created by Admin on 2017/12/4.
 */
@Api(value = "紧急信息管理接口", description = "紧急信息管理接口")
@Controller
@RequestMapping("/urgInfoManage")
@Slf4j
public class UrgInformationController {

    @Autowired
    private UrgInformationService urgInformationService;

    @Autowired
    private WebSocketEndPoint webSocketEndPoint;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getUrgInfoList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取紧急信息列表",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public JsonResult getUrgInformationList(@ApiParam(value = "页码") @RequestParam int pageNow) {
        JsonResult result = new JsonResult();
        List list = new ArrayList();
        int startRow = pageSize * (pageNow - 1);
        List<UrgInformationModel> urgInformationModels = urgInformationService.getUrgInformationList(startRow, pageSize);
        list.add(urgInformationService.getUrgInfoNumber());
        list.add(urgInformationModels);
        result.setObject(list);
        return result;
    }

    @RequestMapping(value = "/getUrgInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取紧急信心详情",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public JsonResult getUrgInformationById(@ApiParam(value = "id") @RequestParam int id) {
        JsonResult result = new JsonResult();
        UrgInformationModel urgInformationModel = urgInformationService.getUrgInformationById(id);
        if (urgInformationModel != null) {
            result.setObject(urgInformationModel);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("该紧急信息不存在！");
        }
        return result;
    }

    @RequestMapping(value = "/insertUrgInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加紧急信息",httpMethod = "POST",
            response = JsonResult.class, notes = "")
    public JsonResult insertUrgInformation(@ApiParam(value = "紧急信息实体(urgInfomation),公开对象字符串(pubOrg,每个机构名称之间用英文逗号隔开)") @RequestBody Map<String, Object> map) throws IOException {
        JsonResult result = new JsonResult();
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(map.get("urgInformation"));
        String str = "";
        String strPubOrg = "";
        List<String> pubOrgs = (ArrayList<String>) map.get("pubOrg");
        if (pubOrgs != null && !pubOrgs.isEmpty()) {
            for (String pubOrg : pubOrgs) {
                str = str + pubOrg + ",";
            }
            StringBuilder sb = new StringBuilder(str);
            strPubOrg = sb.substring(0, str.length() - 1);
        }

        UrgInformationModel urgInformationModel = mapper.readValue(json, UrgInformationModel.class);
        urgInformationModel.setStatus("待发布");
        urgInformationModel.setPubOrg(strPubOrg);
        int code = urgInformationService.insertUrgInformation(urgInformationModel);
        if (code == 1) {
            result.setCode(1);
            result.setStatus(true);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("添加失败！");
        }

        return result;
    }

    @RequestMapping(value = "/releaseUrgInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "发布紧急信息",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public JsonResult releaseUrgInfo(@ApiParam(value = "id") @RequestParam int id) throws JsonProcessingException {
        JsonResult result = new JsonResult();
        UrgInformationModel context = urgInformationService.getUrgInformationById(id);
        String type = "publish";
        List list = new ArrayList();
        list.add(type);
        list.add(context);
        ObjectMapper jsonMessage = new ObjectMapper();
        String message = jsonMessage.writeValueAsString(list);
        try {
            webSocketEndPoint.sendMessageToAllClient(new TextMessage(message));
        } catch (Exception e) {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("发送失败！");
            return result;
        }

        if (urgInformationService.updateUrgInformationStatus("已发布", id) == 1) {
            result.setCode(1);
            result.setStatus(true);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("紧急信息发送成功，但信息发送状态更新失败！");
        }

        return result;
    }

    @RequestMapping(value = "/updateUrgInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "更新紧急信息",httpMethod = "POST",
            response = JsonResult.class, notes = "")
    public JsonResult updateUrgInformationById(@ApiParam(value = "紧急信息实体") @RequestBody UrgInformationModel urgInformationModel) {
        JsonResult result = new JsonResult();
        int code = urgInformationService.updateUrgInformationById(urgInformationModel);
        if (code == 1) {
            result.setCode(1);
            result.setStatus(true);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("更新失败！");
        }

        return result;
    }

    @RequestMapping(value = "/deleteUrgInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除紧急信息",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public JsonResult deleteUrgInformation(@ApiParam(value = "id") @RequestParam int id) {
        JsonResult result = new JsonResult();
        int code = urgInformationService.deleteUrgInformationById(id);
        if (code == 1) {
            result.setCode(1);
            result.setStatus(true);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("删除失败！");
        }
        return result;
    }

    @RequestMapping(value = "/revokeUrgInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "撤销紧急信息",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public JsonResult updateUrgInformationStatus(@ApiParam(value = "id") @RequestParam int id, @ApiParam(value = "撤销人用户名") @RequestParam String revocation) throws JsonProcessingException {
        JsonResult result = new JsonResult();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String revokeTime = dateFormat.format(new Date());
        UrgInformationModel context = urgInformationService.getUrgInformationById(id);
        String organization = userService.getUserByUsername(revocation).getOrganization();
        context.setRevokeTime(revokeTime);
        context.setRevocation(revocation);
        context.setRevokeOrg(organization);
        String type = "revoke";
        List list = new ArrayList();
        list.add(type);
        list.add(context);
        ObjectMapper mapper = new ObjectMapper();
        String message = mapper.writeValueAsString(list);
        if (context.getStatus().equals("已发布")) {
            try {
                webSocketEndPoint.sendMessageToAllClient(new TextMessage(message));
            } catch (Exception e) {
                result.setCode(0);
                result.setStatus(false);
                result.setMsg("撤销信息发送失败！");
                return result;
            }
        }

        if (urgInformationService.updateUrgInformationStatus("未发布", id) == 1 && urgInformationService.updateUrgInformationById(context) == 1) {
            result.setCode(1);
            result.setStatus(true);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("撤销信息发送成功，但信息发送状态更新失败！");
        }
        return result;
    }

}
